#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
@author: LiangChao
@email：kevinleong1011@hotmail.com
@desc: 
"""
import atexit
import threading

from makitest.manage import mk


class ContextData(dict):
    def __getattr__(self, item):
        v = self.get(item)
        if v is None:
            try:
                v = super().__getattribute__(item)
            except AttributeError:
                return None
        return v


class TestContext:
    def __init__(self, parameters=None, **kwargs):
        self.parameters = parameters or {}
        self.data = ContextData(**kwargs)
        self.changed_status = []
        self._threading_nodes = {}  # 按线程存储的测试节点字典
        self.fixture = None  # test_root 是 测试树结构的根节点，统一为TestFixture
        mk.contexts.append(self)

    def push_status(self, status):
        self.changed_status.append(status)

    def reset(self, changer=None):
        for status in reversed(self.changed_status):
            if status.changed and (not changer or status.changed_by == changer):
                status.recover(self)

    def add_threading_node(self, test_node):
        thread_id = threading.current_thread().ident
        self._threading_nodes[thread_id] = test_node

    def current_test(self):
        thread_id = threading.current_thread().ident
        return self._threading_nodes.get(thread_id)


mk.default_context = default_context = TestContext()

atexit.register(default_context.reset)  # 保证非用例模式下执行仍能完成恢复
